package com.lwm.handler;

import com.lwm.domain.ResponseResult;
import com.lwm.utils.Code;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import sun.misc.Contended;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 */
@RestControllerAdvice(annotations = {RestController.class, Contended.class})
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResponseResult<Object> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.error(e.getMessage());
        if (e.getMessage().contains("Duplicate entry")) {
            String[] arr = e.getMessage().split(" ");
            String msg = arr[2] + "已存在";
            return new ResponseResult<>(Code.REPEAT_ENTRY_ERR, msg);
        }
        return new ResponseResult<>(500, "未知错误");
    }
}
